<template>
  <div class="app-container">
    <div class=" p-24 flex flex-col gap-8" data-testid="inbound-order-details-page">
      <div>
        <el-button type="text" @click="returnInventory" icon="el-icon-back">
          返回库存
        </el-button>
      </div>
      <h1 class="w_D6 w_D7 w_EB mt-8 mb-16" data-testid="page-title">库存日志</h1>
      <div class="Card-module_card__zeE7r Card-module_medium__quHDO" v-if="productData">
        <div class="flexxx flex-row">
          <el-image v-if="productData" :src="productData.imageUrl" alt="log item image"
            style="max-height: 100px; max-width: 100px;" fit="contain" :preview-src-list="[productData.imageUrl]">
          </el-image>
          <div class="ml-24">
            <div>
              <p class="w_DY w_Db w_De">{{ productData.productName }}</p>
            </div>
            <div class="mt-8">
              <div class="w_DY w_Dc w_Dd flex gap-4">
                <div class="w_DY w_Dc w_De">GTIN:</div>{{ productData.gtin }}
              </div>
              <div class="w_DY w_Dc w_Dd flex gap-4 mt-8">
                <p class="w_DY w_Dc w_De">SKU:</p>{{ productData.sku }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="Card-module_card__zeE7r Card-module_medium__quHDO p-0 pt-16 overflow-hidden flex flex-col gap-16">
      <div class="input-container">
        <el-input placeholder="Search" v-model="searchInput" @keyup.enter.native="inventoryLogQuery"
          class="input-with-selects">
          <el-select v-model="select" slot="prepend" placeholder="请选择" class="select-input">
            <el-option label="事件类型" value="1"></el-option>
            <el-option label="位置代码" value="2"></el-option>
          </el-select>
          <el-button slot="append" icon="el-icon-search" @click="inventoryLogQuery"></el-button>
        </el-input>
        <div class="div-filters" @click="drawer = true">
          <i class="el-icon-s-operation"></i>
          <span>筛选({{ selectedFiltersCount }})</span>
        </div>
        <div class="div-filters" @click="downDrawer = true">
          <i class="el-icon-lightning"></i>
          <span>下载</span>
        </div>
      </div>
      <div class="div-items">
        <el-table v-loading="loading" :data="inventoryLogList" style="width: 100%" height="500px">
          <el-table-column label="日期" align="center" width="150" sortable prop="transactionTime">
            <template slot-scope="scope">
              {{ parseTime(scope.row.transactionTime, "{y}-{m}-{d} {h}:{i}:{s}") }}
            </template>
          </el-table-column>
          <el-table-column label="事件类型" align="center" prop="transactionType">
          </el-table-column>
          <el-table-column label="描述" align="center" prop="transactionReasonDesc">
          </el-table-column>
          <el-table-column label="地点" align="center" prop="transactionLocation">
          </el-table-column>
          <el-table-column label="配送中心" align="center" prop="fcName">
          </el-table-column>
          <el-table-column label="发货编号" align="center" prop="shipmentId">
          </el-table-column>
          <el-table-column label="单位" align="center" prop="changedUnits" sortable>
          </el-table-column>
        </el-table>
      </div>
      <div style="margin-top: -11px; height: 50px">
        <pagination v-show="total > 0" :total="total" :page.sync="queryParam.pageNum" :limit.sync="queryParam.pageSize"
          @pagination="inventoryLogQuery()" />
      </div>
    </div>

    <el-drawer title="筛选" :visible.sync="drawer" :direction="direction" :size="450">
      <div class="collapse-div">
        <el-collapse v-model="activeNames">
          <el-collapse-item name="1">
            <template slot="title">
              <div>
                选择事件类型
                <br />
                <div v-if="!activeNames || activeNames.length === 0">
                  <el-tag :key="eventType" v-for="eventType in eventTypeList" closable :disable-transitions="false"
                    @close="handleEventType(eventType)">
                    {{ eventType }}
                  </el-tag>
                </div>
              </div>
            </template>
            <el-radio-group v-model="eventTypeList">
              <el-radio label="All">All</el-radio><br />
              <el-radio label="Receipt">Receipt</el-radio><br />
              <el-radio label="Adjustment">Adjustment</el-radio><br />
              <el-radio label="Ship">Ship</el-radio><br />
            </el-radio-group>
          </el-collapse-item>
          <el-collapse-item name="2">
            <template slot="title">
              <div>
                选择位置
                <br />
                <div v-if="!activeNames || activeNames.length === 0">
                  <el-tag :key="location" v-for="location in locationList" closable :disable-transitions="false"
                    @close="handleLocatione(location)">
                    {{ location }}
                  </el-tag>
                </div>
              </div>
            </template>
            <el-radio-group v-model="locationList">
              <el-radio label="All">All</el-radio><br />
              <el-radio label="Inventory">Inventory</el-radio><br />
              <el-radio label="Salvage">Salvage</el-radio><br />
            </el-radio-group>
          </el-collapse-item>
        </el-collapse>
      </div>
      <!-- 按钮部分 -->
      <div class="footer-buttons">
        <el-button type="default" @click="clearAll">清除</el-button>
        <el-button type="primary" @click="applyFilters">应用</el-button>
      </div>
    </el-drawer>

    <el-drawer title="下载库存日志" :visible.sync="downDrawer" :direction="direction" :size="450">
      <div class="collapse-div">
        <el-radio-group v-model="downloadOption" class="download-options" @change="handleDownloadOptionChange">
          <!-- 选择导出范围 -->
          <el-radio label="currentPage">当前页面</el-radio><br />
          <el-radio label="allProducts">所有商品</el-radio><br />
          <el-radio label="customRange">自定义时间段</el-radio>
        </el-radio-group>

        <!-- 当选择“所有商品”时 -->
        <div v-if="downloadOption === 'allProducts'">
          <el-alert v-if="showAlert" title="此项包含的日志条数超过 3000 条，这是下载限制。请选取较窄的日期范围。" type="warning" />
        </div>

        <!-- 选择时间范围 -->
        <div v-if="downloadOption === 'customRange'">
          <el-radio-group v-model="timeRangeOption" @change="processOrderDate">
            <el-radio label="Last 7 days">过去7天</el-radio><br />
            <el-radio label="Last 30 days">过去30天</el-radio><br />
            <el-radio label="customRange">自定义时间段</el-radio>
          </el-radio-group>

          <!-- 自定义时间段 -->
          <div v-if="timeRangeOption === 'customRange'">
            <el-date-picker v-model="dateRange" type="daterange" placeholder="选择日期" range-separator="至"
              start-placeholder="开始日期" end-placeholder="结束日期" style="width: 100%;"
              @change="processOrderDate"></el-date-picker>
          </div>
        </div>
      </div>
      <!-- 按钮部分 -->
      <div class="footer-buttons">
        <el-button type="default" @click="clearDown">清除</el-button>
        <el-button :disabled="isDisabled" type="primary" @click="downFilters">下载</el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { getList } from "@/api/walmart/items";
import { getInventoryLogList } from "@/api/walmart/inventory";
export default {
  data() {
    return {
      queryParam: {
        pageNum: 1,
        pageSize: 50,
        authId: null,
        sku: null,
        gtin: null,
      },
      productData: null,
      select: "1",
      // 遮罩层
      loading: true,
      inventoryLogList: [],
      // 总条数
      total: 0,
      searchInput: "",
      drawer: false,
      activeNames: ['1', '2'],
      eventTypeList: "",
      direction: "rtl",
      locationList: "",
      downDrawer: false,
      downloadOption: 'currentPage', // 默认选择“当前页面”
      timeRangeOption: '',  // 默认选择“过去7天”
      dateRange: [],             // 自定义时间段的起始和结束日期
      showAlert: false,          // 是否显示警告提示
      isDisabled: false          // 控制“应用”按钮是否禁用
    };
  },
  computed: {
    // 计算已选的过滤器数量
    selectedFiltersCount() {
      let count = 0;
      if (this.eventTypeList.length > 0) count++;
      if (this.locationList.length > 0) count++;
      return count;
    },
    filteredOptions() {
      // 根据 activeTab 动态过滤选项
      return this.allOptions[this.activeName] || [];
    },
  },
  mounted() {
    const inventoryData = localStorage.getItem("inventoryData");
    const rowData = JSON.parse(inventoryData);
    this.queryParam.sku = rowData.sku;
    this.queryParam.gtin = rowData.gtin;
    this.queryParam.authId = rowData.authId;
    this.getItemsList();
    this.getInventoryLogList();
  },
  methods: {
    returnInventory() {
      this.$router.replace("/sale/walmart/walmartWFS/inventory");
    },
    getItemsList() {
      getList(this.queryParam).then((response) => {
        if (response && response.rows && response.rows.length > 0) {
          this.productData = response.rows[0];
        }
      });
    },
    inventoryLogQuery() {
      if (this.select == "1") {
        this.queryParam.transactionTypePara = this.searchInput;
        this.getInventoryLogList();
      } else if (this.select == "2") {
        this.queryParam.transactionLocationPara = this.searchInput;
        this.getInventoryLogList();
      }
    },
    getInventoryLogList() {
      this.loading = true;
      getInventoryLogList(this.queryParam).then((response) => {
        this.loading = false;
        this.inventoryLogList = response.rows;
        this.total = response.total;
        if (this.total > 3000) {
          this.showAlert = true;
          this.isDisabled = true;
        }
      });
    },
    // 清除所有选项
    clearAll() {
      this.eventTypeList = "";
      this.locationList = "";
    },
    // 应用筛选条件
    applyFilters() {
      this.queryParam.transactionType = "";
      this.queryParam.transactionLocation = "";
      if (this.eventTypeList != 'All') {
        this.queryParam.transactionType = this.eventTypeList;
      }
      if (this.locationList != 'All') {
        this.queryParam.transactionLocation = this.locationList;
      }
      this.drawer = false;
      this.getInventoryLogList();
    },
    handleEventType() {
      this.eventTypeList = "";
    },
    handleLocation() {
      this.locationList = "";
    },
    clearDown() {
      this.downloadOption = 'currentPage'; // 重置为默认选择
      this.timeRangeOption = 'last7Days';  // 重置为默认选择
      this.dateRange = [];
      //this.showAlert = false;  // 清除警告提示
      //this.isDisabled = false; // 使应用按钮可点击
    },
    handleDownloadOptionChange() {
      if (this.downloadOption === 'currentPage') {
        this.isDisabled = false;
      } else if (this.downloadOption === 'allProducts') {
        if (this.total > 3000) {
          this.showAlert = true;
          this.isDisabled = true;
        }
      } else if (this.downloadOption === 'customRange') {
        this.checkTimeRangeSelection();
      }
    },
    downFilters() {
      // 根据用户选择的下载选项进行处理
      if (this.downloadOption === 'currentPage') {
        this.downloadCurrentPageData();
      } else if (this.downloadOption === 'allProducts') {
        this.downloadAllProductsData();
      } else if (this.downloadOption === 'customRange') {
        this.downloadCustomRangeData();
      }
    },
    //下载当前数据
    downloadCurrentPageData() {
      // 下载当前页面数据
      const csvData = this.convertToCSV(this.inventoryLogList);
      const sku = this.productData.sku;
      const fileName = `${sku}_库存日志.csv`;
      this.downloadFile(csvData, fileName);
    },
    //下载所有数据
    downloadAllProductsData() {
      this.queryParam.pageNum = 1;
      this.queryParam.pageSize = 3000;
      this.loading = true;
      getInventoryLogList(this.queryParam).then((response) => {
        this.loading = false;
        const csvData = this.convertToCSV(response.rows);
        const sku = this.productData.sku;
        const fileName = `${sku}_库存日志.csv`;
        this.downloadFile(csvData, fileName);
      });
    },
    //下载自定义时间数据
    downloadCustomRangeData() {
      this.queryParam.pageNum = 1;
      this.queryParam.pageSize = 3000;
      this.loading = true;
      getInventoryLogList(this.queryParam).then((response) => {
        this.loading = false;
        const csvData = this.convertToCSV(response.rows);
        const sku = this.productData.sku;
        const fileName = `${sku}_库存日志.csv`;
        this.downloadFile(csvData, fileName);
      });
    },
    convertToCSV(data) {
      const headers = ['日期', '事件类型', '描述', '地点', '配送中心', '发货编号', '单位'];
      const rows = data.map(item => [
        this.formatDate(item.transactionTime), item.transactionType,
        item.transactionReasonDesc, item.transactionLocation, item.fcName, item.shipmentId, item.changedUnits
      ]);
      const csvContent = [headers.join(','), ...rows.map(row => row.join(','))].join('\n');
      return csvContent;
    },
    downloadFile(content, filename) {
      const blob = new Blob([content], { type: 'text/csv;charset=utf-8;' });
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = filename;
      link.click();
    },
    // 格式化日期
    formatDate(dateString) {
      const date = new Date(dateString);
      // 获取年、月、日、小时、分钟、秒数
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      const seconds = date.getSeconds().toString().padStart(2, '0');
      // 返回格式化后的日期，格式为 yyyy-MM-dd HH:mm:ss
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },

    // 处理 orderDateList，转换为具体的日期范围
    processOrderDate() {
      this.isDisabled = true;
      const pacificTimezone = "America/Los_Angeles";
      const today = new Date(
        new Date().toLocaleString("en-US", { timeZone: pacificTimezone })
      );
      const formattedDate = this.getFormattedDate(today); // 获取美西时区的日期
      switch (this.timeRangeOption) {
        case "Last 7 days":
          this.checkTimeRangeSelection();
          const sevenDaysAgo = new Date(today);
          sevenDaysAgo.setDate(today.getDate() - 7);
          this.queryParam.startDate = this.getFormattedDate(sevenDaysAgo) + " 00:00:00"; // 7 天前开始
          this.queryParam.endDate = formattedDate + " 23:59:59"; // 今天结束
          break;
        case "Last 30 days":
        this.checkTimeRangeSelection();
          const thirtyDaysAgo = new Date(today);
          thirtyDaysAgo.setDate(today.getDate() - 30); // 30 天前
          this.queryParam.startDate = this.getFormattedDate(thirtyDaysAgo) + " 00:00:00"; // 30 天前开始
          this.queryParam.endDate = formattedDate + " 23:59:59"; // 今天结束
          break;
        case "customRange":
          if (this.dateRange && this.dateRange.length === 2) {
            this.checkTimeRangeSelection();
            // 处理自定义日期范围
            this.queryParam.startDate = this.getFormattedDate(this.dateRange[0]) + " 00:00:00"; // 自定义开始日期
            this.queryParam.endDate = this.getFormattedDate(this.dateRange[1]) + " 23:59:59"; // 自定义结束日期
          }
          break;

        default:
          this.queryParam.startDate = null;
          this.queryParam.endDate = null;
      }
    },
    checkTimeRangeSelection() {
      if (!this.timeRangeOption) {
        // 没有选中任何时间范围
        this.isDisabled = true;
      } else {
        // 有选中时间范围
        this.isDisabled = false; // 可以启用下载按钮
      }
    },
    getFormattedDate(date) {
      // 从已传入的美西时间提取日期部分
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, "0");
      const day = date.getDate().toString().padStart(2, "0");

      // 返回符合 MySQL 格式的 YYYY-MM-DD 日期字符串
      return `${year}-${month}-${day}`;
    },
  }
};
</script>

<style>
input[aria-hidden=true] {
  display: none !important;
}

.Card-module_medium__quHDO {
  padding: 16px;
}

.Card-module_card__zeE7r {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 2px 1px rgba(0, 0, 0, .15);
  box-sizing: border-box;
  width: 100%;
}

.flexxx {
  display: flex !important;
}

.mb-16 {
  margin-bottom: 16px !important;
}

.mt-8 {
  margin-top: 8px !important;
}

.w_EB {
  font-weight: 700;
}

.w_De {
  font-weight: 700;
}

.w_Db {
  font-size: 1rem;
}

.w_Da,
.w_Db {
  line-height: 1.5rem;
}

.mt-8 {
  margin-top: 8px !important;
}

.w_DY {
  color: #2e2f32;
  font-family: Bogle, Helvetica Neue, Helvetica, Arial, sans-serif;
  margin-bottom: 0;
  margin-top: 0;
}

.gap-4 {
  grid-gap: 4px !important;
  gap: 4px !important;
}

.w_Dd {
  font-weight: 400;
}

.w_Dc {
  font-size: .875rem;
  line-height: 1.25rem;
}

.w_DY {
  color: #2e2f32;
  font-family: Bogle, Helvetica Neue, Helvetica, Arial, sans-serif;
  margin-bottom: 0;
  margin-top: 0;
}

.ml-24 {
  margin-left: 24px !important;
}

.collapse-div {
  margin-left: 20px;
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.collapse-div .el-collapse-item__header {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  height: auto;
  line-height: 48px;
  background-color: #ffffff;
  color: #000000;
  cursor: pointer;
  border-bottom: 1px solid #e6ebf5;
  font-size: 15px;
  font-weight: 500;
  -webkit-transition: border-bottom-color 0.3s;
  transition: border-bottom-color 0.3s;
  outline: none;
}

.el-drawer__header {
  font-weight: bold;
  color: #000;
  font-size: 22px;
  /* 增大筛选的标题 */
}

.el-radio {
  font-size: 18px;
  margin-bottom: 10px;
  /* 设置下方间距为 20px，可以根据需要调整 */
  margin-top: 10px;
  /* 设置上方间距为 20px，可以根据需要调整 */
}

/* 设置底部按钮区域 */
.footer-buttons {
  position: absolute;
  /* 相对于 el-drawer 容器固定 */
  bottom: 0;
  left: 0;
  width: 100%;
  background-color: #fff;
  display: flex;
  justify-content: center;
  /* 居中对齐按钮 */
  gap: 10px;
  /* 按钮之间的间距 */
  padding: 10px 15px;
  border-top: 1px solid #eaeaea;
  box-shadow: 0 -1px 5px rgba(0, 0, 0, 0.1);
}

.footer-buttons .el-button {
  border-radius: 20px;
  /* 圆角按钮 */
  padding: 10px 20px;
  /* 调整按钮内边距 */
  font-size: 14px;
  /* 调整字体大小 */
  width: 40%;
}

.footer-buttons .el-button--primary {
  background-color: #007bff;
  /* 蓝色主按钮背景色 */
  color: #fff;
  /* 主按钮文字颜色 */
  border: none;
  /* 去除边框 */
}

.footer-buttons .el-button--default {
  border: 1px solid #ccc;
  /* 次按钮的边框颜色 */
  color: #000;
  /* 次按钮文字颜色 */
  background-color: #fff;
  /* 次按钮背景色 */
}

.checkbox-group .el-checkbox {
  display: block;
  /* 强制每个复选框换行 */
  padding-top: 10px;
}

.div-filters {
  width: 100px;
  height: 36px;
  border: 1px solid #e3e1e1;
  border-radius: 5px;
  margin-left: 10px;
  /* 调整距离，根据需要进行修改 */
  display: flex;
  align-items: center;
  justify-content: center;
}

.div-filters i {
  margin-right: 5px;
  /* 调整距离，根据需要进行修改 */
}

.div-filters span {
  font-size: 14px;
  /* 设置字体大小，根据需要进行修改 */
}

.div-items {
  margin-top: 20px;
}

.input-with-selects {
  width: 1480px;
}

.input-with-selects .el-input-group__prepend {
  background-color: #fff;
}

.input-container {
  display: flex;
  align-items: center;
  margin-left: 6px;
}

.input-with-selects {
  width: 1480px;
}

.input-with-selects .el-input-group__prepend {
  background-color: #fff;
}
</style>
